<template>
    <view class="payment-container">
        <!-- 结算历史 -->
        <view class="history-section">
            <view class="section-title">结算历史</view>
            <view class="room-list">
                <view v-for="room in settledRooms" :key="room.roomId" class="room-card" @click="goToSettleDetail(room.roomId)">
                    <view class="room-header">
                        <text class="room-id">房间号：{{ room.roomId }}</text>
                        <text class="settle-time">{{ formatTime(room.settleTime) }}</text>
                    </view>
                    <view class="room-summary">
                        <text class="summary-text">
                            {{ getSummaryText(room) }}
                        </text>
                    </view>
                    <view class="members-preview">
                        <view v-for="member in room.members" :key="member.openId" class="member-item">
                            <image class="member-avatar" :src="member.avatarUrl" mode="aspectFill"></image>
                            <text class="member-name">{{ member.nickname }}</text>
                            <text class="member-score" :class="{ 'score-positive': member.score > 0, 'score-negative': member.score < 0 }">{{ member.score > 0 ? '+' : '' }}{{ member.score }}</text>
                        </view>
                    </view>
                </view>
                <view v-if="settledRooms.length === 0" class="empty-tip">暂无结算记录</view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            settledRooms: [], // 已结算的房间列表
            page: 1,
            pageSize: 10,
            loading: false,
            hasMore: true,
            userInfo: null,
        };
    },
    onLoad() {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
            this.userInfo = userInfo;
            this.loadSettledRooms();
        }
    },
    onPullDownRefresh() {
        this.page = 1;
        this.hasMore = true;
        this.loadSettledRooms().then(() => {
            uni.stopPullDownRefresh();
        });
    },
    onReachBottom() {
        if (this.hasMore && !this.loading) {
            this.page++;
            this.loadSettledRooms();
        }
    },
    methods: {
        getSummaryText(room) {
            const currentMember = room.members.find(m => m.openId === this.userInfo.openId);
            if (!currentMember) return '';

            if (currentMember.score > 0) {
                return `在本局中您赢得了 ${currentMember.score} 分`;
            } else if (currentMember.score < 0) {
                return `在本局中您输掉了 ${Math.abs(currentMember.score)} 分`;
            } else {
                return '在本局中您打平了';
            }
        },
        async loadSettledRooms() {
            if (this.loading) return;
            this.loading = true;

            try {
                const result = await uniCloud.callFunction({
                    name: 'room',
                    data: {
                        action: 'getSettledRooms',
                        data: {
                            page: this.page,
                            pageSize: this.pageSize,
                            openId: this.userInfo.openId,
                        },
                    },
                });

                if (result.result.code === 0) {
                    const rooms = result.result.data;
                    if (this.page === 1) {
                        this.settledRooms = rooms;
                    } else {
                        this.settledRooms.push(...rooms);
                    }
                    this.hasMore = rooms.length === this.pageSize;
                    console.log('加载结算房间成功:', rooms);
                }
            } catch (e) {
                console.error('加载结算房间失败:', e);
                uni.showToast({
                    title: '加载失败',
                    icon: 'none',
                });
            } finally {
                this.loading = false;
            }
        },
        goToSettleDetail(roomId) {
            uni.navigateTo({
                url: `/pages/settle/settle?roomId=${roomId}`,
            });
        },
        formatTime(timestamp) {
            const date = new Date(timestamp);
            return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
    },
};
</script>

<style>
.payment-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20rpx;
}

.history-section {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
}

.room-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.room-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.room-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.room-id {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.settle-time {
    font-size: 24rpx;
    color: #999;
}

.room-summary {
    margin: 16rpx 0;
    padding: 16rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
}

.summary-text {
    font-size: 28rpx;
    color: #666;
}

.members-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.member-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
}

.member-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
}

.member-name {
    font-size: 24rpx;
    color: #666;
    margin: 4rpx 0;
}

.member-score {
    font-size: 24rpx;
    font-weight: 500;
}

.score-positive {
    color: #52c41a;
}

.score-negative {
    color: #ff4d4f;
}

.empty-tip {
    padding: 40rpx;
    text-align: center;
    color: #999;
    font-size: 28rpx;
}
</style>
